package cn.shop.dys.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.markmao.pulltorefresh.widget.XListView;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.shop.dys.R;
import cn.shop.dys.adapter.LVRightAdapter;
import cn.shop.dys.adapter.ProductAdapter;
import cn.shop.dys.adapter.SuperAdapter;
import cn.shop.dys.bean.ListFilterBean;
import cn.shop.dys.bean.ProductListBean;
import cn.shop.dys.bean.ProductListItem;
import cn.shop.dys.bean.ValueListBean;
import cn.shop.dys.constant.CommonConstant;
import cn.shop.dys.widget.FreeFilterView;
import cn.shop.lib_common.CommonUtil;

/**
 * Created by sugar0811 on 2istShow016/4/19.
 */
public class ProductListShowActivity extends Activity implements AbsListView.OnScrollListener, LVRightAdapter.CallBack, XListView.IXListViewListener {
    private String CID_KEYWORD;
    private String CID_KEYWORD_VALUE;
    private String listType;
   // private String HOST = "http://10.0.2.2:8080/market/";
    private String HOST= CommonConstant.HOST;
    private DrawerLayout drawer;
    private RelativeLayout rl;
    private ListView lv_drawere_right;
    private TextView lastView;
    private TextView textView;
    private List<ValueListBean> firstValueList;
    private List<ValueListBean> thirdValueList;
    private List<ValueListBean> secondValueList;
    private LVRightAdapter lvRightAdapter;
    private RequestParams requestParams;
    private HttpUtils httpUtils;
    private String filter;
    private PopupWindow popupWindow;
    private LinearLayout selector;
    private XListView lv_product_list;
    private SuperAdapter superAdapter;
    private int page = 0;
    private Handler handler = new Handler();
    private String typeId;
    private String sListType = "productlist";
    // 排序默认是销量
    private String orderByValue = "saleDown";
    private boolean isCid;
    private TextView titleView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_product_list);
        initdata();
        initView();

    }

    private void initdata() {
        Intent intent = getIntent();
        // 新品上架------热门单品  只需要  put一下  list_type
        String listType = intent.getStringExtra("singleListType");
        titleView = (TextView) findViewById(R.id.tv_title);
        if (listType != null) {

            this.listType = listType;
        } else {
            // 不是上述两种，就要传bundle 了
            String listTypeKey = intent.getStringExtra("key");
            if (listTypeKey != null) {
                if (listTypeKey.equals("topic/plist")) {

                    titleView.setText("专题列表");
                } else if (listTypeKey.equals("brand/plist")){

                    titleView.setText("品牌专区");
                }//listType
                this.listType = listTypeKey;
            }
        }
        String keyword = intent.getStringExtra("keyword"); // 各路id
        if (keyword != null) {
            CID_KEYWORD = "keyword";
            CID_KEYWORD_VALUE = keyword;


        } else {
            // 可能是cID -- 三级分类
            String cId = intent.getStringExtra("cId");
            if (cId != null) {
                // 是三级分类进来的 设置筛选可见
                CID_KEYWORD = "cId";
                this.listType = "productlist";
                CID_KEYWORD_VALUE = cId;
                isCid = true;
                selector = (LinearLayout) findViewById(R.id.selector);
                selector.setVisibility(View.VISIBLE);
                selector.setOnClickListener(drawRightListener);
            } else {
                // 不是三级分类  那就是品牌和专题了
                String typeId = intent.getStringExtra("id");
                this.typeId = typeId;

            }
        }

    }


    private boolean isSelect;


    OnItemClickListener filterListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TextView selectText = (TextView) view;
            saveEveryState(selectText);
            boolean isFilter = (boolean) selectText.getTag();
            if (isFilter) {
                selectViews.put(selectText, position);
            } else {

                selectViews.remove(selectText);

            }


        }
    };

    private void saveEveryState(TextView this_text) {

        if (this_text.getTag() == null) {

            this_text.setTag(isSelect);
        }
        boolean tag = !(boolean) this_text.getTag();
        this_text.setTag(tag);
        this_text.setTextColor(tag ? Color.RED : Color.GRAY);
        this_text.setBackgroundResource(tag ? R.drawable.selected : R.drawable.shape_selsect_text_bg);
    }

    private void initView() {
        lv_product_list = (XListView) findViewById(R.id.lv_product_list);
        initXlistView();
        rl = (RelativeLayout) findViewById(R.id.rl);
        drawer = (DrawerLayout) findViewById(R.id.drawer);
        View drawer_right = findViewById(R.id.drawer_right);
        lv_drawere_right = (ListView) findViewById(R.id.lv_drawere_right);
        donwLoadData();

    }

    private void initXlistView() {
        lv_product_list.setEmptyView(View.inflate(this, R.layout.layout_empty, null));
        lv_product_list.setPullLoadEnable(true);
        lv_product_list.setPullRefreshEnable(true);
        lv_product_list.setAutoLoadEnable(false);
        lv_product_list.setXListViewListener(this);
        String currentTime = CommonUtil.getCurrentTime();
        lv_product_list.setRefreshTime(currentTime);
    }

    // 返回 finish
    public void back_up(View v) {

        finish();

    }


    private void donwLoadData() {
        httpUtils = new HttpUtils();
        //String HOST = "http://10.0.2.2:8080/market/productlist"
        //productlist?page=0&pageNum=10&orderby=saleDown&cId=22&filter=t1
        RequestParams requestParams = setRequestParams("0", "10", typeId, orderByValue, CID_KEYWORD_VALUE, filter);

        httpUtils.send(HttpRequest.HttpMethod.GET, CommonConstant.HOST +"/" +listType, requestParams, callBack);

    }

    private RequestParams setRequestParams(String page, String pageNum, String typeId, String orderby, String cIdOrkeyWord, String filter) {

        RequestParams requestParams = new RequestParams();
        requestParams.addQueryStringParameter("page", page);
        requestParams.addQueryStringParameter("pageNum", pageNum);
        if (typeId != null) {
            requestParams.addQueryStringParameter("id", typeId);
        }
        ;
        requestParams.addQueryStringParameter("orderby", orderby);
        if (cIdOrkeyWord != null) {
            requestParams.addQueryStringParameter(CID_KEYWORD, cIdOrkeyWord);
        }
        if (filter != null) {

            requestParams.addQueryStringParameter("filter", filter);

        }
        return requestParams;
    }

    private List<ProductListItem> productListItem;
    private List<ListFilterBean> listFilter;
    RequestCallBack<String> callBack = new RequestCallBack<String>() {


        @Override
        public void onSuccess(ResponseInfo<String> responseInfo) {
            String result = responseInfo.result;
            Gson gson = new Gson();
            ProductListBean productListBean = gson.fromJson(result, ProductListBean.class);
            if (isCid) {
                // 筛选条件集合
                listFilter = productListBean.getListFilter();

                // 筛选框的各个集合;
                firstValueList = listFilter.get(0).getValueList();
                secondValueList = listFilter.get(1).getValueList();
                thirdValueList = listFilter.get(2).getValueList();
            }
            // 商品信息集合
            productListItem = productListBean.getProductList();
            setAdapter();
            if(productListItem != null && listType.equals("search")) {
                titleView.setText("搜索结果(共找到 " + productListItem.size() + " 条数据)");
                titleView.setTextSize(14);
            }
//            initDrawRight(listFilter);
        }

        @Override
        public void onFailure(HttpException e, String s) {
            Log.e("onFailure", "失败了");
        }
    };




    private void setAdapter() {
//        gv_main.setAdapter(new ProductAdapter(this, productListItem));
        superAdapter = new SuperAdapter(ProductListShowActivity.this, productListItem);
        lv_product_list.setAdapter(superAdapter);
        if(isCid){
        if (lvRightAdapter == null) {
            lvRightAdapter = new LVRightAdapter(this, listFilter);
            lvRightAdapter.setCallBack(this);
            lv_drawere_right.setAdapter(lvRightAdapter);
        }
    }
    }

    private List<String> filters;
    View.OnClickListener drawRightListener = new View.OnClickListener() {


        @Override
        public void onClick(View v) {
            drawer.openDrawer(rl);
            ids.clear();
            filters = new ArrayList<String>();
            lv_drawere_right.setAdapter(lvRightAdapter);
            isShowFirst = false;
            isShowSecond = false;
            isShowThirdly = false;
        }
    };


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


    // 显示tabs点击的弹窗
    private void showPopupWindowAndSetBackgroud(View v, String first, String second, int viewId) {
        textView = (TextView) v.findViewById(viewId);
        if (lastView != null) {

            lastView.setTextColor(Color.GRAY);
        } else {

            lastView = (TextView) findViewById(R.id.tv_tab_sale);
            lastView.setTextColor(Color.GRAY);
        }
        lastView = textView;
        textView.setTextColor(0xffED165C);
        if (viewId == R.id.tv_tab_price) {
            View contentView = View.inflate(this, R.layout.view_integrated_dialog, null);
            TextView firstTextView = (TextView) contentView.findViewById(R.id.first_);
            TextView secondTextView = (TextView) contentView.findViewById(R.id.second_);
            firstTextView.setText(second);
            secondTextView.setText(first);
            popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            popupWindow.setAnimationStyle(R.style.AnimationPop);
            popupWindow.setTouchable(true);
            View parentView = v;
            int[] location = new int[2];
            // 获取视图在窗体中的绝对位置
            parentView.getLocationInWindow(location);
            float y = v.getY();
            popupWindow.setFocusable(true);
            int height = v.getHeight();
            popupWindow.showAtLocation(parentView, 0, location[0], location[1] + height + 3);

        }
    }

    // 价格的升序
    public void order_Up(View v) {
        // saleDown(销量降序)，priceUp(价格升序)，priceDown(价格降序)，commentDown(评价降序)，
        // shelvesDown(上架降序)。目前只有价格有双向排序，其他都只有降序，其中默认为saleDown
        showOrder("priceUp");

    }

    private void showOrder(String orderBy) {
        if (orderBy.equals("priceUp") || orderBy.equals("priceDown")) {
            popupWindow.dismiss();
        }
        orderByValue = orderBy;
        RequestParams requestParams = setRequestParams("0", "10", typeId, orderBy, CID_KEYWORD_VALUE, null);

        httpUtils.send(HttpRequest.HttpMethod.GET, CommonConstant.HOST+"/" + listType, requestParams, callBack);
    }

    // 价格的降序
    public void order_Down(View v) {

        showOrder("priceDown");

    }


    // tab _ 按照价格排序
    private boolean isSelectMe;

    public void tab_show_price(View v) {
        showPopupWindowAndSetBackgroud(v, "价格从高到低", "价格从低到高", R.id.tv_tab_price);
    }

    // tab _ 按照评价排序
    public void tab_show_comment(View v) {
        showPopupWindowAndSetBackgroud(v, "", "", R.id.tv_tab_comment);
        showOrder("commentDown");
    }

    // tab _ 按照销量排序
    public void tab_show_sale(View v) {
        showPopupWindowAndSetBackgroud(v, "", "", R.id.tv_tab_sale);
        showOrder("saleDown");
    }

    public void tv_tab_time(View v) {
        showPopupWindowAndSetBackgroud(v, "", "", R.id.tv_tab_time);
        showOrder("shelvesDown");

    }

    // 爱心动画 --》么么哒

    public void like_me(View v) {

        AnimationSet animationSet = new AnimationSet(this, null);
        AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
        alphaAnimation.setDuration(2000);
        ScaleAnimation scaleAnimation = new ScaleAnimation(1, 10, 1, 10, v.getWidth() / 2, v.getHeight() / 2);
        scaleAnimation.setDuration(2000);
        animationSet.addAnimation(alphaAnimation);
        animationSet.addAnimation(scaleAnimation);
        v.startAnimation(animationSet);
        View parent = (View) v.getParent();
        TextView tv_like_count = (TextView) parent.findViewById(R.id.tv_like_count);
        String s = tv_like_count.getText().toString().trim();
        int i = Integer.valueOf(s) + 1;
        tv_like_count.setText(" " + i);
    }

    private void showAllSelect(FreeFilterView filterView, List<ValueListBean> data, boolean isWhat) {

        filterView.setItems(data);
        filterView.setVisibility(isWhat ? View.VISIBLE : View.GONE);
        filterView.setOnItemClickListener(filterListener);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
            if (view.getCount() - 1 == view.getLastVisiblePosition()) {
//                Toast.makeText(this, "最后一个", Toast.LENGTH_SHORT).show();
            }

        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    public void reset(View v) {
        // 重置

        for (TextView selectView : selectViews.keySet()) {
            selectView.setBackgroundResource(R.drawable.shape_selsect_text_bg);
            selectView.setTextColor(Color.GRAY);
            selectView.setTag(false);
        }
        selectViews.clear();

    }

    private boolean isShowFirst;
    private boolean isShowThirdly;
    private boolean isShowSecond;

    public void showItems(int position, FreeFilterView freeFilterView, boolean isShowWhat) {
        List<ValueListBean> valueList = listFilter.get(position).getValueList();
        showAllSelect(freeFilterView, valueList, isShowWhat);
    }

    Map<TextView, Integer> selectViews = new HashMap<TextView, Integer>();

    @Override
    public void onClickFilter(int id, FreeFilterView freeFilterView) {
        if (id == R.id.bt_first) {
            // 点击的第一个过滤器
            isShowFirst = !isShowFirst;
            showItems(0, freeFilterView, isShowFirst);
        }
        if (id == R.id.bt_second) {
            // 点击的第二个过滤器
            isShowSecond = !isShowSecond;
            showItems(1, freeFilterView, isShowSecond);
        }
        if (id == R.id.bt_thirdly) {
            // 点击的第三个过滤器
            isShowThirdly = !isShowThirdly;
            showItems(2, freeFilterView, isShowThirdly);
        }
    }

    Map<String, String> ids = new HashMap<String, String>();

    public void confirm(View v) {
        if (selectViews != null) {
            for (TextView selectView : selectViews.keySet()) {
                String itemString = selectView.getText().toString();
                FreeFilterView parent = (FreeFilterView) selectView.getParent();
                int position = selectViews.get(selectView);
                if (parent.getId() == R.id.item_show_first) {
                    // 1的最终的筛选id   ---   id;
                    String key1 = firstValueList.get(position).getKey(itemString);
                    ids.remove("first");
                    ids.put("first", key1);
                }
                if (parent.getId() == R.id.item_show_second) {
                    // 2的最终的筛选id   ---   id;
                    String key2 = secondValueList.get(position).getKey(itemString);
                    ids.remove("second");
                    ids.put("second", key2);
                }
                if (parent.getId() == R.id.item_show_thirdly) {
                    // 3的最终的筛选id   ---   id;
                    String key3 = thirdValueList.get(position).getKey(itemString);
                    ids.remove("third");
                    ids.put("third", key3);

                }
            }
        }
        drawer.closeDrawer(rl);
        selectViews.clear();
        Collection<String> collectionValues = ids.values();
        ArrayList<String> values = new ArrayList<>();
        values.addAll(collectionValues);
        if (!values.isEmpty()) {
            String finalSelect = null;
            StringBuilder stringBuilder = new StringBuilder();
            for (String value : values) {
//     //oductlist?page=0&pageNum=10&orderby=saleDown&cId=22&filter=t1-s1-p8
                if (values.size() == 1) {

                    finalSelect = value;
                } else {
                    if (value != values.get(values.size() - 1)) {
                        stringBuilder.append(value + "-");
                    } else {

                        stringBuilder.append(value);
                    }

                }

            }
            if (stringBuilder.toString() != "") {

                finalSelect = stringBuilder.toString();
            }

            RequestParams requestParams = setRequestParams("0", "10", "saleDown", typeId, CID_KEYWORD_VALUE, finalSelect);
            this.listType = sListType;
            httpUtils.send(HttpRequest.HttpMethod.GET, CommonConstant.HOST+"/" + listType, requestParams, callBack);
        }

    }

    @Override
    public void onRefresh() {
        if (productListItem == null) return;
        // 说明服务器的数据都没10条，就不去请求数据了
        if (productListItem.size() < 10) {

            Toast.makeText(this, "数据是最新的，亲", Toast.LENGTH_SHORT).show();
        } else {

            superAdapter.notifyDataSetChanged();


        }
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                lv_product_list.stopRefresh();
            }
        }, 1000);
    }

    @Override
    public void onLoadMore() {
        if (productListItem == null) return;
        if (productListItem.size() < 5) {

            Toast.makeText(this, "没有数据可以加载了，亲", Toast.LENGTH_SHORT).show();
        } else {
            page += 10;
            RequestParams moreParams = setRequestParams("" + page, typeId, "10", orderByValue, CID_KEYWORD_VALUE, filter);
            httpUtils.send(HttpRequest.HttpMethod.GET, CommonConstant.HOST +"/"+ listType, moreParams, loadMoreCallBack);


        }


        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                lv_product_list.stopLoadMore();
            }
        }, 1000);
    }

    RequestCallBack loadMoreCallBack = new RequestCallBack() {
        @Override
        public void onSuccess(ResponseInfo responseInfo) {
            String result = (String) responseInfo.result;
            Gson gson = new Gson();
            ProductListBean productListBean = gson.fromJson(result, ProductListBean.class);
            List<ProductListItem> moreItems = productListBean.getProductList();
            // List<ProductListItem> productListItem;
            if (moreItems.size() < 10) {

                Toast.makeText(ProductListShowActivity.this, "这是最后一次帮你加载了,兄弟!", Toast.LENGTH_SHORT).show();
            }
            Log.e("moreItems", moreItems.toString());
            productListItem.addAll(moreItems);
            superAdapter.notifyDataSetChanged();
        }

        @Override
        public void onFailure(HttpException e, String s) {

            Log.e("onFailure", "更多失败了");
        }
    };
}
